﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace App {
    public class ErrorMiddlware {

        private readonly RequestDelegate _next;
        private ILogger<ErrorMiddlware> _logger;
        public ErrorMiddlware(RequestDelegate next, ILogger<ErrorMiddlware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var response = context.Response;
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                try
                {
                    var result = new AppResponse<string>(ex);
                    await response.WriteAsJsonAsync(result);
                }
                catch (Exception e)
                {
                    this._logger.LogError(e, "出现异常");
                }
            }
        }
    }

    public static class ErrorMiddlwareExtensions {
        public static IApplicationBuilder UseError(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ErrorMiddlware>();
        }
    }
}
